package the.lb.workbench.auth.controller;

import io.swagger.annotations.ApiParam;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.wisteria.framework.core.exception.BusinessException;
import org.wisteria.framework.web.APIResult;
import org.wisteria.framework.web.util.HttpUtils;
import the.broccoli.setting.service.ILogService;
import the.lb.workbench.auth.po.AuthUser;
import the.lb.workbench.auth.shiro.ShiroUtils;

@RestController
public class LoginController {

    private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private ILogService logService;

    @PostMapping("/login")
    public APIResult login(
            @ApiParam(name = "account", value = "账号", required = true, defaultValue = "139")
            @RequestParam(name = "account") String account,
            @ApiParam(name = "password", value = "密码", required = true, defaultValue = "123456")
            @RequestParam(name = "password") String password,
            @RequestParam(name = "remember", required = false) String remember,
            @RequestParam(name = "captcha", required = false) String captcha
    ) {
        UsernamePasswordToken token = new UsernamePasswordToken(account, password.toCharArray());
        if ("true".equals(remember)) {
            token.setRememberMe(true);
        } else {
            token.setRememberMe(false);
        }

        Subject currSubject = ShiroUtils.getSubject();

        try {
            currSubject.login(token);
        } catch (UnknownAccountException e) {
            LOG.error(e.getMessage());
            throw new BusinessException("账号或密码错误");
        } catch (IncorrectCredentialsException e) {
            LOG.error(e.getMessage(), e);
            throw new BusinessException("账号或密码错误");
        }

        logService.loginLog(account, HttpUtils.getIp());
        return APIResult.success(ShiroUtils.getUser());
    }

    @GetMapping("/logout")
    public APIResult logout() {
        AuthUser authUser = ShiroUtils.getUser();

        ShiroUtils.getSubject().logout();

        logService.logoutLog(authUser.getAccount(), HttpUtils.getIp());
        return APIResult.success();
    }

    @GetMapping("/user-info")
    public APIResult userInfo() {
        return APIResult.success(ShiroUtils.getUser());
    }

    private boolean checkCaptcha(String captcha) {
        return true;
    }
}
